package common.kingdee.cas;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.core.Authentication;

import common.webtools.MyHttpClient;
import net.sf.json.JSONObject;

public class KingdeeTicketAuthenticationSource implements AuthenticationDetailsSource<Authentication, String> {
	@Value(value = "${APPID}")
	private String APPID = null;
	@Value(value = "${SECRET}")
	private String SECRET = null;
	@Value("${host}")
	private String host;
	@Value("${getAppTokenPath}")
	private String getAppTokenPath;
	@Value("${getUserNamePath}")
	private String getUserNamePath;
	private MyHttpClient myHttpClient = new MyHttpClient();

	@Override
	public String buildDetails(final Authentication authentication) {
		List<NameValuePair> forAppTokenParams = new ArrayList<>();
		forAppTokenParams.add(new BasicNameValuePair("grant_type", "client_credential"));
		forAppTokenParams.add(new BasicNameValuePair("appid", APPID));
		forAppTokenParams.add(new BasicNameValuePair("secret", SECRET));
		String forAppTokenUrl = host + getAppTokenPath;
		String appTokenResult = null; 
	try {//"{\"access_token\":\"sssss\"}";
			appTokenResult = myHttpClient.post(forAppTokenUrl, forAppTokenParams);
			if (null != appTokenResult && appTokenResult.trim().length() > 0) {
				JSONObject tokenJson = JSONObject.fromObject(appTokenResult);
				if (tokenJson.containsKey("access_token")) {
					String token = tokenJson.getString("access_token");
					List<NameValuePair> forUserParams = new ArrayList<>();
					forUserParams.add(new BasicNameValuePair("ticket", authentication.getCredentials().toString()));
					forUserParams.add(new BasicNameValuePair("access_token", token));
					// "{\"username\":\"诸成敏\"}";
					String personString = myHttpClient.post(host + getUserNamePath, forUserParams);
					if (null != personString && personString.trim().length() > 0) {
						JSONObject persenJson = JSONObject.fromObject(personString);
						return persenJson.getString("mobile");
					}
				}
			}
		} catch (IOException | HttpException e) {
			e.printStackTrace();
		}
		return null;
	}

}
